package com.fitness.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import com.github.wxpay.sdk.WXPayUtil;

/**
 * 签名的工具类
 * @author nonoy
 *
 */
public class SignUtil {
	
	   // 与接口配置信息中的Token要一致
    private static String token = "gujiayanglao";

    /**
    * 方法名：checkSignature</br>
    * 详述：验证签名</br>
    * @param signature
    * @param timestamp
    * @param nonce
    * @return
    * @throws
     */
    public static boolean checkSignature(String signature, String timestamp,String nonce) {
        // 1.将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = new String[] { token, timestamp, nonce };
        Arrays.sort(arr);
        
        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        
        content = null;
        // 3.将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
    }

    /**
    * 方法名：byteToStr</br>
    * 详述：将字节数组转换为十六进制字符串</br>
    * @param byteArray
    * @return
    * @throws
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
    * 方法名：byteToHexStr</br>
    * 详述：将字节转换为十六进制字符串</br>
    * @param mByte
    * @return
    * @throws
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }

	public static String wx_md5(Map<String, String> param) {
		String perStr = "appId&timeStamp&nonceStr&packag&SignType";
		Map<String, String> map = new HashMap<>();
		map.put("appId", param.get("appid"));
		map.put("timeStamp", param.get("timestamp"));
		map.put("nonceStr", param.get("nonce_str"));
		map.put("signType", "MD5");
		String _package = "prepay_id="+param.get("prepay_id");
		map.put("package", _package);
		String sign = "";
		try {
			sign = WXPayUtil.generateSignature(map, "superstar201805281200hbzbforwxgz");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sign;
	}
	public static String wxApp_md5(Map<String, String> param) {
		Map<String, String> map = new HashMap<>();
		map.put("appid", param.get("appid"));
		map.put("partnerid", param.get("partnerid"));
		map.put("prepayid", param.get("prepay_id"));
		map.put("timestamp", param.get("timestamp"));
		map.put("noncestr", param.get("nonce_str"));
		map.put("package", "Sign=WXPay");
		String sign = "";
		try {
			sign = WXPayUtil.generateSignature(map, "Zrq7xMRZVANnBM0I3my26tyTnlr1q2Gc");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sign;
	}
	
	
	/**
	 * 字典排序
	 * @param param
	 * @return
	 */
	public static String dictionarySort(Map<String, String> param) {
		Set<String> keySet = param.keySet();
		String[] keyArray = keySet.toArray(new String[keySet.size()]);
		Arrays.sort(keyArray);
		StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (param.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(param.get(k).trim()).append("&");
        }
        sb.deleteCharAt(sb.length()-1);
		return sb.toString();
	}
	
	/**
	 * 接收map 对参数进行签名
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static String sha1(Map<String, String> param) throws Exception {
		return sha1(dictionarySort(param)).toUpperCase();
	}
	public static String sha1(String sort) throws Exception{
		java.security.MessageDigest md = MessageDigest.getInstance("sha-1");
		 byte[] array = md.digest(sort.getBytes("UTF-8"));
		 StringBuilder sb = new StringBuilder();
	        for (byte item : array) {
	            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
	        }
		return sb.toString().toUpperCase();
	}
	
	/**
	 * 生成随机订单号
	 */
	public static String RandomUtil() {
		  SimpleDateFormat simpleDateFormat;

		  simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

		  Date date = new Date();

		  String str = simpleDateFormat.format(date);

		  Random random = new Random();

		  int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数

		  return rannum + str;// 当前时间  
		  }
}
